package com.usian.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.usian.config.RedisClient;
import com.usian.mapper.TbContentCategoryMapper;
import com.usian.mapper.TbContentMapper;
import com.usian.pojo.TbContent;
import com.usian.pojo.TbContentCategory;
import com.usian.pojo.TbContentCategoryExample;
import com.usian.pojo.TbContentExample;
import com.usian.service.ContentService;
import com.usian.utils.AdNode;
import com.usian.utils.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class ContentServiceImpl implements ContentService {

    @Value("${AD_CATEGORY_ID}")
    private Long AD_CATEGORY_ID;

    @Value("${AD_HEIGHT}")
    private Integer AD_HEIGHT;

    @Value("${AD_WIDTH}")
    private Integer AD_WIDTH;

    @Value("${AD_HEIGHTB}")
    private Integer AD_HEIGHTB;

    @Value("${AD_WIDTHB}")
    private Integer AD_WIDTHB;

    @Value("${PORTAL_AD_KEY}")
    private String PORTAL_AD_KEY;

    @Autowired
    private RedisClient redisClient;

    @Autowired
    private TbContentCategoryMapper tbContentCategoryMapper;

    @Autowired
    private TbContentMapper tbContentMapper;

    @Override
    public List<TbContentCategory> selectContentCategoryByParentId(Long id) {
        TbContentCategoryExample tbContentCategoryExample = new TbContentCategoryExample();
        TbContentCategoryExample.Criteria criteria = tbContentCategoryExample.createCriteria();
        criteria.andParentIdEqualTo(id);
        criteria.andStatusEqualTo(1);
        List<TbContentCategory> list = tbContentCategoryMapper.selectByExample(tbContentCategoryExample);
        return list;
    }

    @Override
    public Integer insertContentCategory(Long parentId, String name) {
        TbContentCategory tbContentCategory = new TbContentCategory();
        Date date = new Date();
        tbContentCategory.setParentId(parentId);
        tbContentCategory.setName(name);
        tbContentCategory.setCreated(date);
        tbContentCategory.setUpdated(date);
        tbContentCategory.setStatus(1);
        tbContentCategory.setSortOrder(1);
        tbContentCategory.setIsParent(false);
        Integer num = tbContentCategoryMapper.insertSelective(tbContentCategory);

        TbContentCategory category = tbContentCategoryMapper.selectByPrimaryKey(parentId);
        if(!category.getIsParent()){
            category.setIsParent(true);
            category.setUpdated(new Date());
            tbContentCategoryMapper.updateByPrimaryKeySelective(category);
        }
        return num;
    }

    //递归
    public Integer deleteContentCategoryById(Long categoryId){
        try {
            //根据主键查询
            TbContentCategory category = tbContentCategoryMapper.selectByPrimaryKey(categoryId);
            //判断该条数据是不是父节点，如果是
            if (category.getIsParent()){
                //查询和我平级的数据
                List<TbContentCategory> list = selectContentCategory(category.getId());
                //判断list是否为null
                if (list.size()>0){
                    for (int i = 0; i < list.size(); i++) {
                        TbContentCategory tbContentCategory = list.get(i);
                        //判断如果是父节点，那么继续调用当前方法
                        if (tbContentCategory.getIsParent()){
                            deleteContentCategoryById(tbContentCategory.getId());
                        }else {
                            //如果判断不是父节点，
                            // 1.进行逻辑删除
                            // 2.删除关联表的信息
                            deleteContentCategorydeleteContent(tbContentCategory.getId());
                        }
                        // 3.修改父级的isparent
                        updateIsParent(tbContentCategory.getParentId());
                    }
                }
            }
            //逻辑删除   删除关联表
            deleteContentCategorydeleteContent(category.getId());
            //修改之前，先查看有没有和我同级的数据，如果没有就修改父级的isparent
            updateIsParent(category.getParentId());
            return 1;
        }catch (Exception e){
            return 0;
        }
    }

    //根据id查询
    public List<TbContentCategory> selectContentCategory(Long categoryId){
        //如果是，那么查他的子节点有哪些
        TbContentCategoryExample contentCategoryExample = new TbContentCategoryExample();
        TbContentCategoryExample.Criteria criteria = contentCategoryExample.createCriteria();
        criteria.andParentIdEqualTo(categoryId);
        criteria.andStatusEqualTo(1);
        return tbContentCategoryMapper.selectByExample(contentCategoryExample);
    }

    //逻辑删除   删除关联表
    public void deleteContentCategorydeleteContent(Long contentcategoryid){
        TbContentCategory tbContentCategory = new TbContentCategory();
        tbContentCategory.setId(contentcategoryid);
        tbContentCategory.setStatus(2);
        tbContentCategory.setUpdated(new Date());
        tbContentCategoryMapper.updateByPrimaryKeySelective(tbContentCategory);

        TbContentExample example = new TbContentExample();
        TbContentExample.Criteria exampleCriteria = example.createCriteria();
        exampleCriteria.andCategoryIdEqualTo(tbContentCategory.getId());
        tbContentMapper.deleteByExample(example);
    }

    //修改父级的isparent
    public void updateIsParent(Long parentid){
        List<TbContentCategory> contentCategoryList = selectContentCategory(parentid);
        if (contentCategoryList.size()==0){
            TbContentCategory tbContentCategory = tbContentCategoryMapper.selectByPrimaryKey(parentid);
            tbContentCategory.setUpdated(new Date());
            tbContentCategory.setIsParent(false);
            tbContentCategoryMapper.updateByPrimaryKeySelective(tbContentCategory);
        }
    }





  /*  @Override
    public Integer deleteContentCategoryById(Long categoryId) {
        //根据categoryid查出来当前对象
        TbContentCategory tbContentCategory = tbContentCategoryMapper.selectByPrimaryKey(categoryId);

        if (tbContentCategory.getIsParent()){
            return 0;
        }
        Integer num = null;
        tbContentCategory.setUpdated(new Date());
        tbContentCategory.setStatus(2);
        num = tbContentCategoryMapper.updateByPrimaryKeySelective(tbContentCategory);

        //查出来状态为正常，父id是对象的id的数据
        TbContentCategoryExample tbContentCategoryExample = new TbContentCategoryExample();
        TbContentCategoryExample.Criteria criteria = tbContentCategoryExample.createCriteria();
        criteria.andParentIdEqualTo(tbContentCategory.getParentId());
        criteria.andStatusEqualTo(1);
        List<TbContentCategory> list = tbContentCategoryMapper.selectByExample(tbContentCategoryExample);

        if (list.size()==0) {
            //如果查出来的数据等于一条那么该父id就不是父节点了，我就可以把父id修改为false，然后删除当前数据
            TbContentCategory contentCategory = tbContentCategoryMapper.selectByPrimaryKey(tbContentCategory.getParentId());
            contentCategory.setUpdated(new Date());
            contentCategory.setIsParent(false);
            tbContentCategoryMapper.updateByPrimaryKeySelective(contentCategory);
        }

        //如果查出来的数据大于一条，证明改父id还是父节点，不能修改为false，那我就将子节点状态修改为删除
        TbContentExample example = new TbContentExample();
        TbContentExample.Criteria exampleCriteria = example.createCriteria();
        exampleCriteria.andCategoryIdEqualTo(tbContentCategory.getId());
        tbContentMapper.deleteByExample(example);
        return num;
    }*/

    @Override
    public Integer updateContentCategory(Long id, String name) {
        TbContentCategory tbContentCategory = new TbContentCategory();
        tbContentCategory.setId(id);
        tbContentCategory.setName(name);
        tbContentCategory.setUpdated(new Date());
        Integer num = tbContentCategoryMapper.updateByPrimaryKeySelective(tbContentCategory);
        return num;
    }

    @Override
    public PageResult selectTbContentAllByCategoryId(Integer page, Integer rows, Long categoryId) {
        PageHelper.startPage(page,rows);
        TbContentExample tbContentExample = new TbContentExample();
        TbContentExample.Criteria criteria = tbContentExample.createCriteria();
        criteria.andCategoryIdEqualTo(categoryId);

        List<TbContent> list = tbContentMapper.selectByExampleWithBLOBs(tbContentExample);

        PageInfo<TbContent> pageInfo = new PageInfo<TbContent>(list);
        PageResult pageResult = new PageResult();
        pageResult.setResult(pageInfo.getList());
        pageResult.setTotalPage(pageInfo.getPages());
        pageResult.setPageIndex(pageInfo.getPageNum());
        return pageResult;
    }

    @Override
    public Integer insertTbContent(TbContent tbContent) {
        tbContent.setCreated(new Date());
        tbContent.setUpdated(new Date());
        Integer num = tbContentMapper.insertSelective(tbContent);
        redisClient.hdel(PORTAL_AD_KEY,AD_CATEGORY_ID+"");
        return num;
    }

    @Override
    public Integer deleteContentByIds(Long ids) {
        Integer num = tbContentMapper.deleteByPrimaryKey(ids);
        redisClient.hdel(PORTAL_AD_KEY,AD_CATEGORY_ID+"");
        return num;
    }

    @Override
    public List<AdNode> selectFrontendContentByAD() {
        List<AdNode> adNodeListRedis = (List<AdNode>) redisClient.hget(PORTAL_AD_KEY,AD_CATEGORY_ID+"");
        if (adNodeListRedis!=null){
            return adNodeListRedis;
        }
        TbContentExample tbContentExample =  new TbContentExample();
        TbContentExample.Criteria criteria = tbContentExample.createCriteria();
        criteria.andCategoryIdEqualTo(AD_CATEGORY_ID);
        List<TbContent> tbContents = tbContentMapper.selectByExampleWithBLOBs(tbContentExample);
        List<AdNode> adNodeList = new ArrayList<AdNode>();
        for (TbContent tbContent : tbContents) {
            AdNode adNode = new AdNode();
            adNode.setSrc(tbContent.getPic());
            adNode.setSrcB(tbContent.getPic2());
            adNode.setHref(tbContent.getUrl());
            adNode.setHeight(AD_HEIGHT);
            adNode.setHeightB(AD_HEIGHTB);
            adNode.setWidth(AD_WIDTH);
            adNode.setWidthB(AD_WIDTHB);
            adNodeList.add(adNode);
        }
        redisClient.hset(PORTAL_AD_KEY,AD_CATEGORY_ID+"",adNodeList);
        return adNodeList;
    }
}